# -*- coding: utf-8 -*-

try:
    import pymysql 
except ImportError:
    import MySQLdb as pymysql

import sys
from log import set_log

logger = set_log('debug', 'db.log')


class Database:
    '''
        A mysql-client API for python.
        Default:
        host --> 127.0.0.1
        port --> 3306
        user --> root
        password --> empty string
        db --> mysql
    '''
    def __init__(self, host='127.0.0.1', port=3306, user='root', password='', db='mysql'):
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.db = db

    def _conn(self):
        try:
            conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.password, db=self.db)
        except Exception as err:
            logger.error(err)
        return conn

    def insert(self, sql, values):
        conn = self._conn()
        try:
            cur = conn.cursor()
            cur.execute(sql, values)
            conn.commit()
        finally:
            conn.close()

    def query(self, sql):
        conn = self._conn()
        cur = conn.cursor()
        result = str()
        try:
            try:
                cur.execute(sql)
            except Exception as e:
                logger.error(e)
            result = cur.fetchall()
        finally:
            conn.close()
            return result

    def command(self, sql):
        conn = self._conn()
        cur = conn.cursor()
        result = str()
        try:
            try:
                cur.execute(sql)
            except Exception as e:
                logger.error(e)
        finally:
            conn.close()
            return
